/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Servlet;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author kinder
 */
public class LattesScholarServlet extends HttpServlet {
   
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        
        String url = request.getParameter("urlpesquisador");
         
        /* Cria o arquivo contendo a url do pesquisador */
        try{
            /*Onde o arquivo com a url do pesquisador vai ser criado*/

            File file = new File("U:\\LattesScholar\\url_pesquisador.txt");
            
            //Teste no servidor
            //File file = new File ("C:\\ArquivosLattesScholar\\url_pesquisador.txt");
            FileWriter writer = new FileWriter(file);
            PrintWriter saida = new PrintWriter(writer,true);

            
            saida.println(url);
            saida.close();
            writer.close();
        
        }
    	catch(IOException e){
            System.out.println("Erro ao criar arquivo "+e.getMessage());
    	}

        /* Espera a escrita do arquivo com as obras e número de citações */

        boolean existFile = false;
    	while (!existFile){
            File file;
            try{
                /*De onde o arquivo com as citacoes vai ser lido*/
                String caminhoArquivo = ("U:\\LattesScholar\\citacoes.log");
                
                //Teste no servidor
                //String caminhoArquivo = ("C:\\ArquivosLattesScholar\\citacoes.log");
                file = new File(caminhoArquivo);
                FileReader reader = new FileReader(file);
                BufferedReader bReader = new BufferedReader(reader);

                existFile = true;
                /* Exibe o resultado para o usuário */
                response.setContentType("text/html;charset=UTF-8");
                PrintWriter out = response.getWriter();
                try {
                    /* TODO output your page here */
                    out.println("<html>");
                    out.println("<head>");
                    out.println("<title>Lattesscholar</title>");
                    out.println("<link rel=\"stylesheet\" type=\"text/css\" href=\"css\\estilo.css\">");
                    out.println("</head>");
                    out.println("<body>");
                    out.println("<br />");
                    out.println("<br />");
                    out.println("<div align=center ><h2>Citações</h2>");
                    out.print("<table cellpadding=10>");
                    String linha = "";
                    out.println("<tr>");
                    out.println("<td align=center><p style='font-family: times, serif; font-size:14pt; font-style:italic font-weight:bold'>Título</p></td>");
                    out.println("<td align=center><p style='font-family: times, serif; font-size:14pt; font-style:italic font-weight:bold'>Número de citações</p></td>");
                    out.print("</tr>");
                    while((linha = bReader.readLine())!=null)  {
                        int indexCitacoes = linha.indexOf("==");
                        if (indexCitacoes > 0){
                            String qtdCitacoes = linha.substring(indexCitacoes+2);
                            String titulo = linha.substring(0, indexCitacoes);
                            out.println("<tr>");
                            out.println("<td><p style='font-family: times, serif; font-size:11pt; font-style:italic'>"+titulo+"</p></td>");
                            out.println("<td align=center><p style='font-family: times, serif; font-size:11pt; font-style:italic'>"+qtdCitacoes+"</p></td>");
                            out.print("</tr>");
                        }else{
                            out.println("<tr>");
                            out.println("<td><p style='font-family: times, serif; font-size:11pt; font-style:italic'>"+linha+"</p></td>");
                            out.println("<td align=center><p style='font-family: times, serif; font-size:11pt; font-style:italic'>"+""+"</p></td>");
                            out.print("</tr>");
                        }

                        
                    }
                    out.println("</body>");
                    out.println("</html>");
                    out.print("</table>");
                } finally {
                    out.close();
                }

                try{
                    bReader.close();
                    if (file.delete()){
                        System.out.println("Arquivo apagado com sucesso");
                    }else{
                        System.out.println("Não foi possivel apagar o arquivo");
                    }
                }catch (Exception e){
                    System.out.println("Erro ao apagar arquivo "+e.getMessage());
                }

            }catch(Exception e){}
        }

        /* Exibe o resultado para o usuário */
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        /*
        try {
            /* TODO output your page here 
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Contexto do     LattesScholarServlet</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet LattesScholarServlet at " +getServletContext().getContextPath()+ "</h1>");
            out.println("</body>");
            out.println("</html>");
            
        } finally { 
            out.close();
        }
        */
    } 

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
